package customer

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/utils"
	"gorm.io/gorm"
)

type customerRepo struct {
	tenant_db.TenantDB
}

func NewCustomerRepo() CustomerRepoIface {
	return &customerRepo{}
}

func (c *customerRepo) QueryCustomer(ctx context.Context, condition map[string]interface{}, pageInfo *utils.PageInfo) (int64, []*Customer, error) {
	db := c.GetTenantDB(ctx).Table(Customer{}.TableName()).Where("__IsDeleted = ?", constants.IsDeletedFalse)

	if companyNameList, ok := condition["CustomerNameList"]; ok {
		db.Where("CustomerName in (?)", companyNameList)
		delete(condition, "CustomerNameList")
	}

	db = db.Where(condition)
	var count int64
	var queryList []*Customer
	err := db.Count(&count).Error
	if err != nil {
		return 0, nil, err
	}

	if pageInfo != nil && pageInfo.Page > 0 && pageInfo.PageSize > 0 {
		db = db.Offset((pageInfo.Page - 1) * pageInfo.PageSize).Limit(pageInfo.PageSize)
	}
	if err = db.Find(&queryList).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return 0, nil, nil
		}
		return 0, nil, err
	}
	return count, queryList, nil
}

func (c *customerRepo) SaveCustomer(ctx context.Context, po *Customer) error {
	return c.GetTenantDB(ctx).Create(po).Error
}

// GetCustomerInfoByUid 根据客户ID获取客户信息
func (c *customerRepo) GetCustomerInfoByUid(ctx context.Context, customerUid string) (*Customer, error) {
	costmoter := &Customer{}
	err := c.GetTenantDB(ctx).
		Where("CustomerGUID = ? ", customerUid).
		Find(costmoter).
		Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil && err == gorm.ErrRecordNotFound {
		return nil, nil
	}
	return costmoter, nil
}

func (c *customerRepo) GetCustomerCloundData(ctx context.Context, customerPoolGUID string) (*Customerpoolclouddata, error) {
	customerCloundData := &Customerpoolclouddata{}
	err := c.GetTenantDB(ctx).
		Where("CustomerPoolGUID = ? ", customerPoolGUID).
		First(customerCloundData).
		Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil && err == gorm.ErrRecordNotFound {
		return nil, nil
	}
	return customerCloundData, nil
}

func (c *customerRepo) SaveCustomerCloud(ctx context.Context, po *Customerpoolclouddata) error {
	return c.GetTenantDB(ctx).Create(po).Error
}
